package com.itmake.sample.dynamic.aspectj;

import com.itmake.sample.dynamic.annotation.DataSource;
import com.itmake.sample.dynamic.handler.DynamicHandler;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 多数据源切换
 *
 * @author Amjacks
 * @since 2023/08/10
 */
@Aspect
@Order(1)
@Component
public class DataSourceAspect {

    @Pointcut("@annotation(com.itmake.sample.dynamic.annotation.DataSource)"
            + "|| @within(com.itmake.sample.dynamic.annotation.DataSource)")
    public void dsPointCut() {}

    @Around("dsPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        // 获取需要切换的数据源
        MethodSignature signature = (MethodSignature) point.getSignature();
        DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
        dataSource = Objects.nonNull(dataSource) ? dataSource :
                AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
        // 设置数据源
        String curDb = null;
        if (Objects.nonNull(dataSource)) {
            // 原来的数据源
            curDb = DynamicHandler.getDataSourceType();
            DynamicHandler.setDataSourceType(dataSource.value().name());
        }
        try {
            return point.proceed();
        } finally {
            if (Objects.nonNull(curDb)) {
                // 还原数据源
                DynamicHandler.setDataSourceType(curDb);
            } else if (Objects.nonNull(dataSource)) {
                // 销毁数据源 在执行方法之后
                DynamicHandler.clearDataSourceType();
            }
        }
    }
}
